package com.pentofab.payrollmanagement.ui.controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView.ResizeFeatures;
import javafx.scene.layout.VBox;
import javafx.util.Callback;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.EmployeeDao;
import com.pentofab.payrollmanagement.dao.model.BankInfo;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.Units;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;

public class BankInfoController extends AbstractUIController
		implements Initializable {

	@FXML
	VBox root;
	@FXML
	private TableView bankInfoTab;
	private Company company;
	private UserAccounts userAccounts;
	private BankInfo bankInfo;
	
	@Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {

		return "Bank Information";
	}

	@Override
	public void refreshUI(Object... args) {
		
		
		if (args != null && args.length > 0) {
			Company company = (Company) args[0];
			this.company = company;
			
			if(args.length > 1 && args[1] instanceof UserAccounts){
				userAccounts = (UserAccounts) args[1];
			}
		}

		EmployeeDao empDao = PayrollApplicationFactory.getEmployeeMgmt();
		try {
			ArrayList<BankInfo> bankInfo = empDao.getBankInfo(null);
			this.populateTable(bankInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void add() {
		
		PayrollApplicationFactory.getMainController().showScreen(
				MainController.AddBankInfo, true, this.company);
	}

	public void edit() {
		
		if (null != null) {
			PayrollApplicationFactory.getMainController().showScreen(
					MainController.AddBankInfo, true, this.company,bankInfo);
		} else {
			showError("Select an Unit to edit");
		}
	}
	
	public void goBack() {

		PayrollApplicationFactory.getMainController().showScreen(
				MainController.COMPANIES_LIST_SCREEN, false, userAccounts);
	}
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {

		
	}

	private void populateTable(final ArrayList<BankInfo> bankInfoList ) {
    	
	    System.out.println("====================== entering populateTable in =================================");
	    final String header = "Bank Code,Name,ISFC Code,Address,Zipcode,Telephone1,Telephone2,Fax,EmailId";
	    Task<Void> task = new Task<Void>() {
	      @Override
	      protected Void call() throws Exception {
	        if (true) {
	          final String headerLine =header.toString();
	          final String[] headerValues = headerLine.split(",");
	          System.out.println("headerLine : "+headerValues.length);
	          Platform.runLater(new Runnable() {
	            @Override
	            public void run() {
	              for (int column = 0; column < headerValues.length; column++) {
	            	  bankInfoTab.getColumns().add(
	                    createColumn(column, headerValues[column].trim()));
	              }
	            }
	          });
	        }        
	       System.out.println(bankInfoTab.getColumns().size());
	        
	        Iterator<BankInfo> bankInfoListIterator  = bankInfoList.iterator();
	        while (bankInfoListIterator.hasNext()) {
	        	
	        	BankInfo current = bankInfoListIterator.next();
	        	String[] colnms = new String[9];
	        	colnms[0] = current.getBankCode();
	        	colnms[1] = current.getName();
	        	colnms[2] = current.getISFCCode();
	        	colnms[3] = current.getAddress();
	        	colnms[4] = current.getZipcode();
	        	colnms[5] = current.getTelephone1();
	        	colnms[6] = current.getTelephone2();
	        	colnms[7] = current.getFax();
	        	colnms[8] = current.getMailId();
	        	
	        	StringBuffer rowData = new StringBuffer();
				
				for(int i = 0;i< colnms.length;i++){
					
					rowData.append(colnms[i]);
					if(i< colnms.length -1){
						rowData.append(",");
					}
				}
	        	

				System.out.println("bankInfoTab.getColumns().size() ; "+bankInfoTab.getColumns().size());
	        	final String[] dataValues = rowData.toString().split(",");
	        	
	        	System.out.println("dataValues "+dataValues.length);
	        	Platform.runLater(new Runnable() {
	        		@Override
	        		public void run() {
	        			// Add additional columns if necessary:
	        			for (int columnIndex = bankInfoTab.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
	        				bankInfoTab.getColumns().add(createColumn(columnIndex, ""));
	        			}
	        			// Add data to table:
	        			ObservableList<StringProperty> data = FXCollections.observableArrayList();
	        			for (String value : dataValues) {
	        				data.add(new SimpleStringProperty(value));
	        			}
	        			bankInfoTab.getItems().add(data);
	        		}
	        	});
	        }
	        
	        System.out.println(bankInfoTab.getColumns().size());
	        return null;
	      }
	    };
	    Thread thread = new Thread(task);
	    thread.setDaemon(true);
	    thread.start();
	    thread.run();
	    System.out.println("====================== entering populateTable out =================================");
	  }
	
	 private TableColumn<ObservableList<StringProperty>, String> createColumn(
   	      final int columnIndex, String columnTitle) {
   	    TableColumn<ObservableList<StringProperty>, String> column = new TableColumn<ObservableList<StringProperty>, String>();
   	    String title;
   	    if (columnTitle == null || columnTitle.trim().length() == 0) {
   	      title = "Column " + (columnIndex + 1);
   	    } else {
   	      title = columnTitle;
   	    }
   	    column.setText(title);
   	    column.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<StringProperty>, String>, ObservableValue<String>>() {
   	          @Override
   	          public ObservableValue<String> call(
   	              CellDataFeatures<ObservableList<StringProperty>, String> cellDataFeatures) {
   	            ObservableList<StringProperty> values = cellDataFeatures.getValue();
   	            if (columnIndex >= values.size()) {
   	              return new SimpleStringProperty("");
   	            } else {
   	              return cellDataFeatures.getValue().get(columnIndex);
   	            }
   	          }
   	        });
   	    
   	    if(columnIndex >3){
   	    	column.setSortable(false);
   	    }
   	    column.setEditable(false);
   	    column.resizableProperty().set(false);
   	    return column;
   	  }

	
}
